#include "map.h"
#include "cube.h"

Map::Map(QWidget *parent, int newX, int newY, QString newfilepath, QString newUsername) :
    QWidget(parent)
{
    counter = 0;
    counter2 = 0;
    startSpeed = 4;
    speed = startSpeed;
    x = newX;
    y = newY;
    up = down = left = right = false;

    this->username = newUsername;

    shipWidth = 4;
    shipOffset = 5;
    this->filepath = newfilepath;

    background = new QImage(newfilepath + "Images/background02.png");
}

void Map::addCube(double newX, double newY, double newZ, int newSize, int  newColor)
{
    cout << "Adding a cube" << endl;
    Cube *newCube = new Cube(this, newX, newY, newZ, newSize, newColor);
}

void Map::camUpdate()
{
    if(up == true)
        if(y > 2)
            y -= 3;
    if(down == true)
        if(y < 45)
            y += 3;
    if(left == true)
        if(x > 1.5)
            x -= 3;
    if(right == true)
        if(x < 48.5)
            x += 3;
}

void Map::getMap()
{
    //load the file
        QFile file(filepath + "/gameData/map01.txt");
        QStringList cubes;
        if (file.open(QIODevice::ReadOnly | QIODevice::Text))
        {
            QTextStream in(&file);

            while (!in.atEnd()) {
                cubes += in.readLine().split("/n");
            }
        }

        //create the cubes
        for (int i = 0; i < cubes.length() - 1; i++)
        {
            QString text = cubes[i];
            i++;
            int xPos = cubes[i].toInt();
            i++;
            int yPos = cubes[i].toInt();
            i++;
            int zPos = cubes[i].toInt();
            i++;
            int size = cubes[i].toInt();
            i++;
            int color = cubes[i].toInt();

            addCube(xPos, yPos, zPos, size, color);
        }

        dynamic_cast<BaseWindow*>(this->parent()->parent())->logEvent("Added cubes to map."); //EVENT LOG

        /* FORMAT FOR MAP TEXT FILE
          -------------------------
          [comment for cube 1]
          [parameter 1 for cube 1]
          [parameter 2 for cube 1]
          [parameter 3 for cube 1]
          [parameter 4 for cube 1]
          [parameter 5 for cube 1]
          [comment for cube 2]
          [parameter 1 for cube 2]
          [parameter 2 for cube 2]
          [parameter 3 for cube 2]
          [parameter 4 for cube 2]
          [parameter 5 for cube 2]
           . . .
           ----------------------
           NOTE: Make sure there are no blank lines at the end of
           the text file! */
}

void Map::loadCubes()
{    
    //Log the username
    dynamic_cast<BaseWindow*>(this->parent()->parent())->logEvent("Name: " + this->username); //EVENT LOG

    //Get the map
    getMap();
    this->speed = this->startSpeed;

    //Reverse-engineer the position of the cubes
    //For every frame...
    for(int i = 1; i < this->counter; i++)
    {
        //Speed up
        int amount = 2;
        int frequency = 2;
        if(i % (frequency*30) == 0)
            this->speed += amount;

        //For each cube in the gameMap...
        QList<Cube *> allCubes = this->findChildren <Cube *>();
        for (int i = allCubes.size() - 1; i >= 0; --i)
        {
            //Z-update (Move the cube forward)
            allCubes[i]->zUpdate();

            //Check for deletion
            if(allCubes[i]->z < -10)
                allCubes[i]->deleteLater();
        }
    }

    this->counter2 = this->counter;
}

void Map::saveMap()
{
    QString filename = QFileDialog::getSaveFileName(this, "Save Form", "", "");
    QFile file(filename);

    if (!file.open(QIODevice::WriteOnly))
    {
        QMessageBox::information(this, tr("Unable to open file"), file.errorString());
    }
    else
    {
        QDataStream out(&file);
        out.setVersion(QDataStream::Qt_4_6); // Change this based on current Qt version

        //output username
        out << this->username;
        // output counter
        out << counter;
        //output x
        out << this->x;
        // output y
        out << this->y;
        //close file
        file.close();

        dynamic_cast<BaseWindow*>(this->parent()->parent())->logEvent("Saved game."); //EVENT LOG
    }
}
void Map::loadMap(){

    QString filename = QFileDialog::getOpenFileName(this, "Load Form", "", "");
    QFile file(filename);

    if (!file.open(QIODevice::ReadOnly))
    {
        //If the user cancels the load, go back to the main menu
        dynamic_cast<BaseWindow*>(this->parent()->parent())->showMainMenu();
        this->parentWidget()->deleteLater();
        this->deleteLater();
    }
    else
    {
        //If the file loads successfully...
        //Delete all the existing cubes
        QList<Cube *> allCubes = this->findChildren <Cube *>();
        for (int i = allCubes.size() - 1; i >= 0; --i)
            allCubes[i]->deleteLater();        

        //Declare variables
        int newcounter, newx, newy, newspeed;
        QString newUsername;

        //Read in the variables.
        QDataStream in(&file);
        in.setVersion(QDataStream::Qt_4_6);

        in >> newUsername;
        in >> newcounter;
        in >> newx;
        in >> newy;

        //Assign properties to object
        this->x = newx;
        this->y = newy;
        this->counter = newcounter;
        this->username = newUsername;

        dynamic_cast<BaseWindow*>(this->parent()->parent())->logEvent("Loaded game."); //EVENT LOG

        //Create the cubes to match these variables.
        this->loadCubes();        
    }
}
